<template>
  <div class="AddOrUpdate_main add_container column_three">
    <el-tabs v-model="activeName">
      <el-tab-pane label="基本信息" name="1">
        <div id="chat" class="main_main">
          <el-form ref="form" style="margin-top:15px !important" :model="formData" :rules="rules" :inline="true">
            <el-form-item label="销售订单号" prop="code">
              <CodeRuleInput
                :band-value.sync="formData.code"
                table-name="sale_order"
                column-name="code"
                :is-edit="id"
              />
            </el-form-item>
            <el-form-item label="销售人员">
              <el-input v-model="formData.orderName" placeholder="暂无" disabled />
            </el-form-item>
            <el-form-item v-if="id" label="制单日期" prop="orderTime">
              <el-date-picker
                v-model="formData.orderTime"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
              />
            </el-form-item>
            <el-form-item label="订单类型">
              <DictSelect
                :band-value.sync="formData.orderTypeCode"
                dict-type="orderTypeCode"
              />
            </el-form-item>
            <el-form-item label="客户名称" class="clickChoose" prop="customerName">
              <!-- <el-select
            v-model="formData.saleCustomerId"

            clearable
            filterable
            placeholder="请选择"
            @change="changePeople"
          >
            <el-option
              v-for="item in peopleList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select> -->
              <el-input v-model="formData.customerName" placeholder="请选择" readonly />
              <a
                class="clickChoose_button"
                @click.prevent="choosePeople"
              >
                <svg-icon icon-class="选择弹框" />
              </a>
            </el-form-item>
            <el-form-item label="交货方式" class="clickChoose">
              <el-input v-model="formData.defaultSaleDeliverInformation.deliveryTypeLabel" placeholder="暂无" readonly />
              <a
                class="clickChoose_button"
                @click.prevent="chooseWays"
              >
                <svg-icon icon-class="选择弹框" />
              </a>
            </el-form-item>
            <el-form-item label="订货日期">
              <el-date-picker
                v-model="formData.orderGoodsTime"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="选择日期"
              />
            </el-form-item>
            <el-form-item label="合同号">
              <el-input v-model="formData.contractCode" placeholder="请输入" clearable />
            </el-form-item>
            <el-form-item label="未税总金额">
              <el-input v-model="formData.allPrice" type="number" placeholder="暂无" />
            </el-form-item>
            <el-form-item label="含税总金额">
              <el-input v-model="formData.taxAllPrice" type="number" placeholder="暂无" />
            </el-form-item>
            <el-form-item label="税额">
              <el-input v-model="formData.tax" type="number" placeholder="暂无" />
            </el-form-item>
            <el-form-item label="附件" class="double">
              <FileManageFull
                :file-names="formData.fileName"
                :file-real-names="formData.fileRealName"
                :file-urls="formData.url"
                :row-index="1"
                @fileName="setFileName"
              />
            </el-form-item>
            <el-form-item label="备注" class="double">
              <el-input
                v-model="formData.remark"
                type="textarea"
                maxlength="200"
                show-word-limit
                placeholder="请输入"
              />
            </el-form-item>
          </el-form>
          <div class="formItem_header">
            <!-- 订单明细 -->
            <div />
            <div class="formItem_header_operate">
              <a class="formItem_header_operate_item" @click="addRow">
                <svg-icon icon-class="新增" />
                <div class="item_name">添加</div>
              </a>
              <a class="formItem_header_operate_item" @click="importOrder">
                <svg-icon icon-class="导入" />
                <div class="item_name">导入</div>
              </a>
              <a class="formItem_header_operate_item delete" @click="deleteRow">
                <svg-icon icon-class="删除" />
                <div class="item_name">删除</div>
              </a>
            </div>
          </div>
          <div
            ref="table_container"
            class="table_container draggableTable"
          >
            <u-table
              ref="table"
              :key="tableKey"
              :data="listData"
              stripe
              border
              use-virtual
              :total-option="totalOption"
              show-summary
              :height="500"
              :row-height="44"
              :cell-class-name="cellClassName"
              :header-cell-class-name="headerCellClassName"
              :row-class-name="rowClassName"
              :header-cell-style="headStyle"
              @table-body-scroll="tableBodyScroll"
              @selection-change="selectionChange1"
            >
              <u-table-column type="selection" align="center" :selectable="canSelect" width="60" />
              <u-table-column label="订单数量" :min-width="SETTINGS.settings_decimalDigits_length" prop="orderNumber" fixed="right">
                <template slot-scope="scope">
                  <el-input v-if="scope.row.status=='0'||scope.row.status=='3'" v-model="scope.row.orderNumber" placeholder="请输入" clearable @input="changeOrder($event,scope.row,scope.$index)" />
                  <span v-else>{{ scope.row.orderNumber }}</span>
                </template>
              </u-table-column>
              <u-table-column label="客户订单号" min-width="200" prop="saleCustomerOrderCode" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                  <el-input v-if="scope.row.status=='0'||scope.row.status=='3'" v-model="scope.row.saleCustomerOrderCode" placeholder="请输入" clearable />
                  <span v-else>{{ scope.row.saleCustomerOrderCode }}</span>
                </template>
              </u-table-column>
              <u-table-column label="物料编码" min-width="120" prop="materialCode" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                  <span>{{ scope.row.materialCode }}</span>
                </template>
              </u-table-column>
              <u-table-column label="物料名称" min-width="100" prop="materialName" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                  <span>{{ scope.row.materialName }}</span>
                </template>
              </u-table-column>
              <u-table-column label="规格型号" min-width="100" prop="materialModel" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                  <span>{{ scope.row.materialModel }}</span>
                </template>
              </u-table-column>
              <u-table-column label="客户料号" min-width="200" prop="saleCustomerMaterialCode">
                <template slot-scope="scope">
                  <el-input v-if="scope.row.status=='0'||scope.row.status=='3'" v-model="scope.row.saleCustomerMaterialCode" placeholder="请输入" clearable />
                  <span v-else>{{ scope.row.saleCustomerMaterialCode }}</span>
                </template>
              </u-table-column>
              <u-table-column label="物料单位" min-width="100" prop="materialUnitName">
                <template slot-scope="scope">
                  <span>{{ scope.row.materialUnitName }}</span>
                </template>
              </u-table-column>

              <u-table-column label="未税单价" :min-width="SETTINGS.settings_decimalDigits_length" prop="price">
                <template slot-scope="scope">
                  <el-input v-if="scope.row.status=='0'||scope.row.status=='3'" v-model="scope.row.price" type="number" placeholder="请输入" clearable @input="changePrice($event,scope.row,scope.$index)" />
                  <span v-else>{{ scope.row.price }}</span>
                </template>
              </u-table-column>
              <u-table-column label="含税单价" :min-width="SETTINGS.settings_decimalDigits_length" prop="taxPrice">
                <template slot-scope="scope">
                  <el-input v-if="scope.row.status=='0'||scope.row.status=='3'" v-model="scope.row.taxPrice" type="number" placeholder="请输入" clearable @input="changeTaxPrice($event,scope.row,scope.$index)" />
                  <span v-else>{{ scope.row.taxPrice }}</span>
                </template>
              </u-table-column>
              <u-table-column label="税率%" min-width="100" prop="taxRateCode">
                <template slot-scope="scope">
                  <el-select
                    v-if="scope.row.status=='0'||scope.row.status=='3'"
                    v-model="scope.row.taxRateCode"
                    clearable
                    filterable
                    placeholder="请选择"
                    @change="changeTaxRateCode($event,scope.row,scope.$index)"
                  >
                    <el-option
                      v-for="item in taxRateCodeList"
                      :key="item.dictCode"
                      :label="item.dictLabel"
                      :value="item.dictCode"
                    />
                  </el-select>
                  <span v-else>{{ scope.row.taxRateLabel }}</span>
                </template></u-table-column>
              <u-table-column label="税额" :min-width="SETTINGS.settings_decimalDigits_length" prop="tax" align="right">
                <template slot-scope="scope">
                  <span>{{ scope.row.tax }}</span>
                  <!-- <span v-else>{{ scope.row.tax }}</span> -->
                </template>
              </u-table-column>
              <u-table-column label="未税总金额" :min-width="SETTINGS.settings_decimalDigits_length" prop="allPrice" align="right">
                <template slot-scope="scope">
                  <span>{{ scope.row.allPrice }}</span>
                  <!-- <span v-else>{{ scope.row.allPrice }}</span> -->
                </template>
              </u-table-column>
              <u-table-column label="含税总金额" :min-width="SETTINGS.settings_decimalDigits_length" prop="taxAllPrice" align="right">
                <template slot-scope="scope">
                  <span>{{ scope.row.taxAllPrice }}</span>
                  <!-- <span v-else>{{ scope.row.allPrice }}</span> -->
                </template>
              </u-table-column>
              <u-table-column label="客户交期" min-width="140" prop="saleCustomerDeliveryTime" fixed="right">
                <template slot-scope="scope">
                  <el-date-picker
                    v-if="scope.row.status=='0' || scope.row.status=='3'"
                    v-model="scope.row.saleCustomerDeliveryTime"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="选择日期"
                    @change="getTime($event,scope.row, scope.$index)"
                  />
                  <span v-else>{{ scope.row.saleCustomerDeliveryTime }}</span>
                </template>
              </u-table-column>
              <u-table-column label="备注" min-width="200" prop="remark">
                <template slot-scope="scope">
                  <el-input v-if="scope.row.status=='0'" v-model="scope.row.remark" placeholder="请输入" clearable />
                  <span v-else>{{ scope.row.remark }}</span>
                </template>
              </u-table-column>
            </u-table>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="客户信息" name="2">
        <div class="main_main customer_info">
          <el-form :model="formData" :inline="true">
            <!-- <el-form-item label="计税方式">
              <el-input v-model="formData.saleCustomerListVo.taxTypeLabel" disabled />
            </el-form-item>
            <el-form-item label="税率%">
              <el-input v-model="formData.saleCustomerListVo.taxRateLabel" disabled />
            </el-form-item>
            <el-form-item label="结算方式">
              <el-input v-model="formData.saleCustomerListVo.settlementTypeLabel" disabled />
            </el-form-item>
            <el-form-item label="结算币别">
              <el-input v-model="formData.saleCustomerListVo.settlementCurrencyLabel" disabled />
            </el-form-item> -->
            <el-form-item label="收货人">
              <el-input v-model="formData.defaultSaleDeliverInformation.consignee" disabled />
            </el-form-item>
            <el-form-item label="联系方式">
              <el-input v-model="formData.defaultSaleDeliverInformation.phone" disabled />
            </el-form-item>
            <el-form-item label="注意事项">
              <el-input v-model="formData.defaultSaleDeliverInformation.attentionMatters" disabled />
            </el-form-item>
            <el-form-item class=" double" label="收货地址">
              <el-input v-model="formData.defaultSaleDeliverInformation.deliveryAddress" type="textarea" disabled />
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>
    </el-tabs>
    <!-- <el-divider />
        <div class="formItem_header">客户信息</div>
        <el-form-item label="计税方式">
          <el-input v-model="formData.saleCustomerListVo.taxTypeLabel" placeholder="暂无" disabled />
        </el-form-item>
        <el-form-item label="税率%">
          <el-input v-model="formData.saleCustomerListVo.taxRateLabel" placeholder="暂无" disabled />
        </el-form-item>
        <el-form-item label="结算方式">
          <el-input v-model="formData.saleCustomerListVo.settlementTypeLabel" placeholder="暂无" disabled />
        </el-form-item>
        <el-form-item label="结算币别">
          <el-input v-model="formData.saleCustomerListVo.settlementCurrencyLabel" placeholder="暂无" disabled />
        </el-form-item>
        <el-form-item label="交货方式" class="clickChoose">
          <el-input v-model="formData.defaultSaleDeliverInformation.deliveryTypeLabel" placeholder="暂无" readonly />
          <a
            class="clickChoose_button"
            @click.prevent="chooseWays"
          >
            <svg-icon icon-class="选择弹框" />
          </a>
        </el-form-item>
        <el-form-item label="收货人">
          <el-input v-model="formData.defaultSaleDeliverInformation.consignee" placeholder="暂无" disabled />
        </el-form-item>
        <el-form-item label="联系方式">
          <el-input v-model="formData.defaultSaleDeliverInformation.phone" placeholder="暂无" disabled />
        </el-form-item>
        <el-form-item label="注意事项">
          <el-input v-model="formData.defaultSaleDeliverInformation.attentionMatters" placeholder="暂无" disabled />
        </el-form-item>
        <el-form-item label="收货地址" class="double">
          <el-input v-model="formData.defaultSaleDeliverInformation.deliveryAddress" type="textarea" placeholder="暂无" disabled />
        </el-form-item> -->

    <!-- </el-form>

    </div> -->
    <div class="main_bottom">
      <div>
        <span v-if="showSchedule" style="color:#999999">明细导入中...({{ progressTitle }}%)</span>
        <span v-if="showSuccess" style="color:#19BE6B">导入成功</span>
        <span v-if="showFail" style="color:#e76c6c">导入失败</span>
      </div>
      <div>
        <el-button type="cancel" @click.stop="cancel">取消</el-button>
        <el-button @click.stop="onSubmit('0')">保存</el-button>
        <el-button @click.stop="onSubmit('1')">提交</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import {
  addOrUpdate,
  getInfo,
  listPriceByCustomer,
  // orderapproval,
  importMethod
} from '@/api/saleManage/saleOrder'
import { getSystemSet } from '@/api/common/systemSet'
// import { list as approvalSettingList } from '@/api/system/approvalSettings'
import { list } from '@/api/saleManage/customerInfo'
import seachUser from './addUser.vue'
import chooseWay from './chooseWay.vue'
import { getDictSelects } from '@/api/common/common'
import moment from 'moment'
import searchMaterial from './searchMaterial.vue'
import ImportData from '@/components/JLink/common/ImportData'
import Big from 'big.js' // big.js解决精度丢失问题
import { mapGetters } from 'vuex'
import _ from 'lodash'
export default {
  name: 'AddOrUpdate',

  props: {
    layerid: {},
    id: {},
    defaultValue: {},
    isAdd: {}
  },
  computed: {
    ...mapGetters([
      'companyId'
    ])
  },
  data() {
    const validateOrderTime = (rule, value, callback) => {
      if (this.formData.orderTime > Date.now()) {
        callback(new Error('制单日期不可超过当前日期'))
      } else {
        callback()
      }
    }
    return {
      pageId: '销售订单明细导入',
      progressTitle: '0',
      showSchedule: false,
      showSuccess: false,
      showFail: false,
      timer: undefined,
      activeName: '1',
      settingList: [],
      table_scrollTop: 0,
      table_scrollLeft: 0,
      pageData: {
        pageNum: 1,
        pageSize: 9999,
        orderByColumn: 'updateTime',
        isAsc: 'desc'
      },
      tableKey: '',
      formData: {
        code: '',
        orderBy: '',
        orderName: '',
        orderTime: '',
        orderTypeCode: '',
        saleCustomerId: '',
        customerName: '',
        orderGoodsTime: '',
        contractCode: '',
        allPrice: '',
        taxAllPrice: '',
        tax: '',
        fileName: '',
        fileRealName: '',
        url: '',
        remark: '',
        saleCustomerListVo: {
          taxTypeLabel: '',
          taxRateLabel: '',
          settlementTypeLabel: '',
          settlementCurrencyLabel: ''
        },
        saleCustomerSendInformationId: '',
        defaultSaleDeliverInformation: {
          deliveryTypeLabel: '',
          consignee: '',
          phone: '',
          deliveryAddress: '',
          attentionMatters: ''
        },
        data: [],
        id: '',
        allOrderNumber: ''
      },
      totalOption: [
        { label: '税额' },
        { label: '未税总金额' },
        { label: '含税总金额' },
        { label: '订单数量' }
      ],
      mainId: 'id',
      selections: [], // 表格当前页所选中的行
      selectionsAll: [], // 表格所有页选中的行
      settings_decimalDigits: '2', // 系统小数保留位数
      listData: [],
      taxRateCodeList: [],
      tableHeight: '',
      showSummary: true,
      templateSelection: '',
      tableData: [],
      peopleList: [],
      selectionsAll1: [],
      saveData: [],
      peopleData: {},
      rules: {
        code: [
          { required: true, message: '销售订单号不能为空', trigger: 'blur' }
        ],
        orderTime: [
          { validator: validateOrderTime, trigger: 'change' }
        ],
        customerName: [
          { required: true, message: '客户名称不能为空', trigger: 'change' }
        ]
      }
    }
  },
  watch: {
    listData() {
      if (this.listData.length > 9) {
        this.tableHeight = '500'
      } else {
        this.tableHeight = ''
      }
      this.$refs['table'].doLayout()
    }
  },
  created() {
    if (!this.id) {
      // 没有id就是新增
      Object.keys(this.defaultValue).forEach((key) => {
        // 给右边数据赋值
        this.formData[key] = this.defaultValue[key]
      })
    } else {
      // 有id就是编辑
      this.getInfo()
      this.formData.id = this.id
    }
  },
  updated() {
    this.$nextTick(() => {
      this.$refs['table'].doLayout()
    })
  },
  mounted() {
    // this.getApprovalSettingList()
    // this.getList()
    this.getDictOptions()
    this.getSystemSet()
    this.formData.orderName = this.$store.state.user.name
    this.formData.orderBy = this.$store.state.user.userId
    this.formData.orderTime = new Date()
    this.formData.orderGoodsTime = moment(new Date()).format('YYYY-MM-DD')
  },
  methods: {
    getTime(e, row, index) {
      if (this.listData.filter(item => item.materialId == row.materialId && item.saleCustomerDeliveryTime == e).length > 1) {
        this.$message.warning('该物料在该交期下已存在，请修改交期或删除明细')
        this.listData[index].saleCustomerDeliveryTime = ''
      }
    },
    // getApprovalSettingList() {
    //   approvalSettingList().then(res => {
    //     this.settingList = res.data.filter(item => item.code == '销售订单')
    //   })
    // },
    getSystemSet() {
      // 获取系统设置数据
      getSystemSet(this.companyId).then(res => {
        // 获取系统设置中的 小数展示位数
        this.settings_decimalDigits = res.data.decimalDigits || 2
      })
    },
    importOrder() { // 导入备件物料
      this.$layer.iframe({// 弹框
        content: {
          content: ImportData, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {}// props
        },
        area: ['440px', '250px'],
        title: '导入数据', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    importMethod(files) { // 导入接口
      importMethod(files, (ps) => {
        this.showSchedule = true
        // this.progressTitle = Math.floor((ps.loaded / ps.total) * 100)
        this.progressTitle = 0
        this.timer = setInterval(() => {
          const num = Math.floor(Math.random() * 20) + 1
          if (this.progressTitle + num < 100) {
            this.progressTitle = this.progressTitle + num
          }
        }, 20)
        // }
      }).then(res => {
        // setTimeout(() => {
        if (res.data) {
          // setTimeout(() => {
          this.$nextTick(() => {
            this.listData = []
            const cacheData = this.$deepClone(res.data)
            /**
             * @Author wssn
             * @Description 计算单价和金额
             * @Date 2024/6/3 16:04
             */
            cacheData.forEach(item => {
              if (item.taxRateLabel) {
                if (item.taxPrice && item.taxPrice != '0') {
                  const cacheData = new Big(item.taxPrice).div(new Big(1).plus(new Big(item.taxRateLabel).div(100).toString())).toString()
                  item.price = parseFloat(Number(cacheData).toFixed(Number(this.settings_decimalDigits))).toString()
                } else if (item.price && item.price != '0') {
                  const cacheData = new Big(item.taxRateLabel).div(100).plus(1).times(item.price)
                  item.taxPrice = parseFloat(Number(cacheData).toFixed(Number(this.settings_decimalDigits))).toString()
                }
              }
              if (item.price && item.price != '0') {
                item.allPrice = new Big(item.price).times(item.orderNumber).toString()
              }
              if (item.taxPrice && item.taxPrice != '0') {
                item.taxAllPrice = new Big(item.taxPrice).times(item.orderNumber).toString()
              }
              if (item.taxAllPrice && item.taxAllPrice != '0' && item.allPrice) {
                item.tax = new Big(item.taxAllPrice).minus(item.allPrice).toString()
              }
            })
            // res.data.forEach(item => {
            //   this.listData.push(item)
            // })
            const arr1 = cacheData.map(item => item.materialId)
            if (this.formData.saleCustomerId) {
              listPriceByCustomer({
                customerId: this.formData.saleCustomerId,
                materialIds: _.uniq(arr1)
              }).then(res => {
                const arr = this.$deepClone(cacheData)
                arr.some(ele => {
                  const data2 = res.data.find(item => item.materialInformationId == ele.materialId)
                  if (data2) {
                    if (!ele.price) {
                      ele.price = data2.price ? data2.price : '0'
                    }
                    if (!ele.taxPrice) {
                      ele.taxPrice = data2.taxPrice ? data2.taxPrice : '0'
                    }
                    if (!ele.taxRateCode) {
                      ele.taxRateCode = data2.taxRateCode ? data2.taxRateCode : ''
                    }
                    if (!ele.taxRateLabel) {
                      ele.taxRateLabel = data2.taxRateLabel ? data2.taxRateLabel : '0'
                    }

                    ele.tax = ele.price && ele.taxRateLabel && ele.orderNumber ? new Big(ele.price).times(ele.taxRateLabel).div(100).times(ele.orderNumber).toString() : '0'
                    ele.taxAllPrice = ele.taxPrice && ele.orderNumber ? new Big(ele.taxPrice).times(ele.orderNumber).toString() : '0'
                    ele.allPrice = ele.price && ele.orderNumber ? new Big(ele.price).times(ele.orderNumber).toString() : '0'
                  }
                })

                this.progressTitle = 100

                this.showSchedule = false
                this.showSuccess = true
                clearInterval(this.timer)
                this.listData = arr

                this.tableKey = Math.random()

                setTimeout(() => {
                  this.showSuccess = false
                }, 1000)

                this.$nextTick(() => {
                  this.formData.tax = 0
                  this.formData.allPrice = 0
                  this.formData.taxAllPrice = 0
                  this.listData.forEach(item => {
                    this.formData.tax = new Big(this.formData.tax).plus(Number(item.tax ? item.tax : 0)).toString()
                    this.formData.allPrice = new Big(this.formData.allPrice).plus(Number(item.allPrice ? item.allPrice : 0)).toString()
                    this.formData.taxAllPrice = new Big(this.formData.taxAllPrice).plus(Number(item.taxAllPrice ? item.taxAllPrice : 0)).toString()
                  })
                })
              })
            } else {
              this.progressTitle = 100

              this.showSchedule = false
              this.showSuccess = true
              clearInterval(this.timer)
              this.listData = cacheData

              this.tableKey = Math.random()

              setTimeout(() => {
                this.showSuccess = false
              }, 1000)

              this.$nextTick(() => {
                this.formData.tax = 0
                this.formData.allPrice = 0
                this.formData.taxAllPrice = 0
                this.listData.forEach(item => {
                  this.formData.tax = new Big(this.formData.tax).plus(Number(item.tax ? item.tax : 0)).toString()
                  this.formData.allPrice = new Big(this.formData.allPrice).plus(Number(item.allPrice ? item.allPrice : 0)).toString()
                  this.formData.taxAllPrice = new Big(this.formData.taxAllPrice).plus(Number(item.taxAllPrice ? item.taxAllPrice : 0)).toString()
                })
              })
            }
          })
          // }, 500)
        }
        // }, 2000)
        // this.progressTitle = 100
      }).catch(() => {
        this.progressTitle = 100
        clearInterval(this.timer)
        this.showSchedule = false
        this.$nextTick(() => {
          this.showFail = true
          setTimeout(() => {
            this.showFail = false
          }, 3000)
        })
      })
    },
    headerCellClassName(data) {
      if (['orderNumber', 'saleCustomerDeliveryTime'].indexOf(data.column.property) != -1) {
        return 'column_bt'
      }
    },
    canSelect(row, index) {
      if (row.status == '0' || row.status == '3') {
        return true
      } else {
        return false
      }
    },
    getDictOptions() {
      getDictSelects('taxRateCode').then(res => {
        this.taxRateCodeList = res.data
      })
    },
    // 合计行
    getSummaries({ columns, data }) {
      const sums = []// 合计
      columns.forEach((column, index) => {
        if (index == 0) {
          sums.push('合计')
        }
        switch (column.property) {
          case 'orderNumber':
            sums[index] = data.map(item => item.orderNumber).reduce((prev, curr) => {
              if (curr) {
                return new Big(prev).plus(curr).toString()
              } else {
                return new Big(prev).toString()
              }
            }, 0)
            this.formData.orderNumber = sums[index]
            break
          case 'tax':
            sums[index] = data.map(item => item.tax).reduce((prev, curr) => {
              if (curr) {
                return new Big(prev).plus(curr).toString()
              } else {
                return new Big(prev).toString()
              }
            }, 0)
            this.formData.tax = sums[index]
            break
          case 'allPrice':
            sums[index] = data.map(item => item.allPrice).reduce((prev, curr) => {
              if (curr) {
                return new Big(prev).plus(curr).toString()
              } else {
                return new Big(prev).toString()
              }
            }, 0)
            this.formData.allPrice = sums[index]
            break
          case 'taxAllPrice':
            sums[index] = data.map(item => item.taxAllPrice).reduce((prev, curr) => {
              if (curr) {
                return new Big(prev).plus(curr).toString()
              } else {
                return new Big(prev).toString()
              }
            }, 0)
            this.formData.taxAllPrice = sums[index]
            break
        }
      })
      return [sums]
    },
    changePeople(e) {
      this.peopleData = this.peopleList.find(item => item.id == e)
      this.formData.saleCustomerListVo.taxTypeLabel = this.peopleData.taxTypeLabel
      this.formData.saleCustomerListVo.taxRateLabel = this.peopleData.taxRateLabel
      this.formData.saleCustomerListVo.settlementTypeLabel = this.peopleData.settlementTypeLabel
      this.formData.saleCustomerListVo.settlementCurrencyLabel = this.peopleData.settlementCurrencyLabel
      if (this.peopleData.defaultSaleDeliverInformation) {
        this.formData.defaultSaleDeliverInformation.deliveryTypeLabel = this.peopleData.defaultSaleDeliverInformation.deliveryTypeLabel
        this.formData.defaultSaleDeliverInformation.consignee = this.peopleData.defaultSaleDeliverInformation.consignee
        this.formData.defaultSaleDeliverInformation.phone = this.peopleData.defaultSaleDeliverInformation.phone
        this.formData.defaultSaleDeliverInformation.deliveryAddress = this.peopleData.defaultSaleDeliverInformation.deliveryAddress
        this.formData.defaultSaleDeliverInformation.attentionMatters = this.peopleData.defaultSaleDeliverInformation.attentionMatters
      }
    },
    // onlyInteger(e, index) {
    //   // const rule = /^[0-9][0-9]*$/
    //   // const num = Number(e)
    //   // if (rule.test(e)) {
    //   //   this.$set(this.listData[index], 'orderNumber', e)
    //   // } else if (e && num !== 0) {
    //   //   this.$message.warning('订单数量必须为整数')
    //   //   this.$set(this.listData[index], 'orderNumber', e.replace('.', ''))
    //   // }
    //   if (e.indexOf('.') > -1) {
    //     const afterPoint = e.split('.')
    //     if (e !== 0 && afterPoint[1].length > 2) {
    //       this.listData[index].orderNumber = e.slice(0, e.indexOf('.') + 3)
    //       this.$message.warning('至多可输入两位小数')
    //     } else if (e == 0) {
    //       this.listData[index].orderNumber = 0
    //     }
    //   } else {
    //     this.listData[index].orderNumber = e
    //   }
    //   const scrollLeft = this.$refs.table.bodyWrapper.scrollLeft // 保存当前横向滚动条位置
    //   this.showSummary = false
    //   this.$nextTick(() => {
    //     this.showSummary = true
    //     this.$refs.table.bodyWrapper.scrollLeft = scrollLeft +0.1
    //     this.$nextTick(() => {
    //       this.$refs.table.bodyWrapper.scrollLeft = scrollLeft
    //       const chat = this.$el.querySelector('#chat')
    //       chat.scrollTop = chat.scrollHeight
    //     })
    //   })
    // },
    // 未税单价
    //  scope.row.price&&scope.row.taxRateCode&&scope.row.orderNumber?(scope.row.price*scope.row.taxRateLabel/100*scope.row.orderNumber):'0.00'
    // scope.row.allPrice=scope.row.orderNumber&&scope.row.price?(Number(scope.row.price)*Number(scope.row.orderNumber))
    // scope.row.taxAllPrice=scope.row.taxPrice&&scope.row.orderNumber?(Number(scope.row.taxPrice)*Number(scope.row.orderNumber
    priceNumber(index, taxPrice, taxRateLabel) {
      console.log('priceNumber', this.listData[index].taxPrice)
      // const priceNumber = new Big(this.listData[index].taxPrice || 0).div(1 + Number(this.listData[index].taxRateLabel) / 100)

      return new Big(this.listData[index].taxPrice || 0).div(new Big(1).plus(new Big(this.listData[index].taxRateLabel).div(100).toString())).toString()
      // console.log(priceNumber,22222)
      // return parseFloat(priceNumber.toFixed(Number(this.settings_decimalDigits))).toString()
      // return new Big(this.listData[index].taxPrice || 0).div(1 + Number(this.listData[index].taxRateLabel) / 100)
      // return new Big(this.listData[index].taxPrice).div(new Big(1).plus(new Big(this.listData[index].taxRateLabel).div(100).toString()).toString()).toString()
    },
    taxPriceNumber(index, price, taxRateLabel) {
      console.log('taxPriceNumber', this.listData[index].price)
      const taxPriceNumber = new Big(this.listData[index].taxRateLabel || 0).div(100).plus(1).times(this.listData[index].price || 0)
      return parseFloat(taxPriceNumber.toFixed(Number(this.settings_decimalDigits))).toString()
      // return new Big(this.listData[index].taxRateLabel || 0).div(100).plus(1).times(this.listData[index].price || 0).toFixed(Number(this.settings_decimalDigits)).toString()
      // return new Big(this.listData[index].price).times(new Big(1).plus(new Big(this.listData[index].taxRateLabel).div(100).toString()).toString()).toString()
    },
    taxNumber(index, price, taxRateLabel, orderNumber) {
      console.log('taxNumber', this.listData[index].price)
      const taxNumber = new Big(this.listData[index].price || 0).times(this.listData[index].taxRateLabel || 0).div(100).times(this.listData[index].orderNumber || 0)
      console.log('1============>', taxNumber)
      console.log('2============>', taxNumber.toFixed(Number(this.settings_decimalDigits)))
      console.log('3============>', parseFloat(taxNumber.toFixed(Number(this.settings_decimalDigits))))
      console.log('4============>', parseFloat(taxNumber.toFixed(Number(this.settings_decimalDigits))).toString())
      return parseFloat(taxNumber.toFixed(Number(this.settings_decimalDigits))).toString()
      // return new Big(this.listData[index].price || 0).times(this.listData[index].taxRateLabel || 0).div(100).times(this.listData[index].orderNumber || 0).toFixed(Number(this.settings_decimalDigits)).toString()
      // return new Big(new Big(new Big(this.listData[index].price).times(this.listData[index].taxRateLabel).toString()).div(100).toString()).times(this.listData[index].orderNumber).toString()
    },
    allPriceNumber(index, price, orderNumber) {
      console.log('allPriceNumber', this.listData[index].price)
      const allPriceNumber = new Big(this.listData[index].price || 0).times(this.listData[index].orderNumber || 0)
      return parseFloat(allPriceNumber.toFixed(Number(this.settings_decimalDigits))).toString()
      // return new Big(this.listData[index].price || 0).times(this.listData[index].orderNumber || 0).toFixed(Number(this.settings_decimalDigits)).toString()
    },
    taxAllPriceNumber(index, taxPrice, orderNumber) {
      console.log('taxAllPriceNumber', this.listData[index].taxPrice)
      const allPriceNumber = new Big(this.listData[index].taxPrice || 0).times(this.listData[index].orderNumber || 0)
      // console.log(parseFloat(allPriceNumber))
      return parseFloat(allPriceNumber.toFixed(Number(this.settings_decimalDigits))).toString()
      // const taxAllPriceNumber = new Big(this.listData[index].taxPrice || 0).times(this.listData[index].orderNumber || 0)
      // console.log(parseFloat(taxAllPriceNumber).toFixed(Number(this.settings_decimalDigits)).toString(), 'parseFloat(taxAllPriceNumber).toFixed(Number(this.settings_decimalDigits)).toString()')
      // return parseFloat(taxAllPriceNumber).toFixed(Number(this.settings_decimalDigits)).toString()
      // return new Big(this.listData[index].taxPrice || 0).times(this.listData[index].orderNumber || 0).toFixed(Number(this.settings_decimalDigits)).toString()
    },
    // 未税单价变化时
    changePrice(e, row, index) {
      this.listData[index].taxPrice = this.listData[index].taxRateCode && e ? this.taxPriceNumber(index) : e
      if (this.listData[index].orderNumber && e) {
        this.listData[index].tax = this.listData[index].taxRateCode ? this.taxNumber(index) : '0'
        this.listData[index].taxAllPrice = this.listData[index].taxRateCode ? this.taxAllPriceNumber(index) : '0'
        this.listData[index].allPrice = this.allPriceNumber(index)
      } else {
        this.listData[index].tax = '0'
        this.listData[index].taxAllPrice = '0'
        this.listData[index].allPrice = '0'
      }

      this.$nextTick(() => {
        this.formData.tax = 0
        this.formData.allPrice = 0
        this.formData.taxAllPrice = 0
        this.listData.forEach(item => {
          this.formData.tax = new Big(this.formData.tax).plus(Number(item.tax ? item.tax : 0)).toString()
          this.formData.allPrice = new Big(this.formData.allPrice).plus(Number(item.allPrice ? item.allPrice : 0)).toString()
          this.formData.taxAllPrice = new Big(this.formData.taxAllPrice).plus(Number(item.taxAllPrice ? item.taxAllPrice : 0)).toString()
          // this.formData.tax += Number(item.tax ? item.tax : 0)
          // this.formData.allPrice += Number(item.allPrice ? item.allPrice : 0)
          // this.formData.taxAllPrice += Number(item.taxAllPrice ? item.taxAllPrice : 0)
        })
        this.fixAccuracyIssues()
      })
    },

    // 订单数量变化时
    changeOrder(e, row, index) {
      if (this.listData[index].taxRateCode && this.listData[index].price && this.listData[index].taxPrice && e) {
        this.listData[index].tax = this.taxNumber(index)
        this.listData[index].allPrice = this.allPriceNumber(index)
        this.listData[index].taxAllPrice = this.taxAllPriceNumber(index)
      } else {
        this.listData[index].tax = '0'
        this.listData[index].allPrice = this.listData[index].price ? this.allPriceNumber(index) : '0'
        this.listData[index].taxAllPrice = '0'
      }

      this.$nextTick(() => {
        this.formData.tax = 0
        this.formData.allPrice = 0
        this.formData.taxAllPrice = 0
        this.listData.forEach(item => {
          this.formData.tax = new Big(this.formData.tax).plus(Number(item.tax ? item.tax : 0)).toString()
          this.formData.allPrice = new Big(this.formData.allPrice).plus(Number(item.allPrice ? item.allPrice : 0)).toString()
          this.formData.taxAllPrice = new Big(this.formData.taxAllPrice).plus(Number(item.taxAllPrice ? item.taxAllPrice : 0)).toString()
        })
        this.fixAccuracyIssues()
      })
    },
    // 含税单价变化时
    changeTaxPrice(e, row, index) {
      this.listData[index].price = this.listData[index].taxRateCode && e ? this.priceNumber(index) : this.listData[index].taxPrice
      if (this.listData[index].orderNumber && e) {
        this.listData[index].tax = this.listData[index].taxRateCode ? this.taxNumber(index) : '0'
        this.listData[index].taxAllPrice = this.listData[index].taxRateCode ? this.taxAllPriceNumber(index) : '0'
        this.listData[index].allPrice = this.allPriceNumber(index)
      } else {
        this.listData[index].tax = '0'
        this.listData[index].taxAllPrice = '0'
        this.listData[index].allPrice = '0'
      }

      this.$nextTick(() => {
        this.formData.tax = 0
        this.formData.allPrice = 0
        this.formData.taxAllPrice = 0
        this.listData.forEach(item => {
          this.formData.tax = new Big(this.formData.tax).plus(Number(item.tax ? item.tax : 0)).toString()
          this.formData.allPrice = new Big(this.formData.allPrice).plus(Number(item.allPrice ? item.allPrice : 0)).toString()
          this.formData.taxAllPrice = new Big(this.formData.taxAllPrice).plus(Number(item.taxAllPrice ? item.taxAllPrice : 0)).toString()
        })

        this.fixAccuracyIssues()
      })
    },
    // 税率变化时
    changeTaxRateCode(e, row, index) {
      this.taxRateCodeList.forEach(ele => {
        if (ele.dictCode == e) {
          this.listData[index].taxRateLabel = ele.dictLabel
        }
      })
      if (this.listData[index].taxPrice) {
        this.listData[index].price = e ? this.priceNumber(index) : this.listData[index].taxPrice
      } else {
        return
      }
      if (this.listData[index].orderNumber && this.listData[index].taxPrice) {
        this.listData[index].tax = e ? this.taxNumber(index) : '0'
        this.listData[index].taxAllPrice = e ? this.taxAllPriceNumber(index) : '0'
        this.listData[index].allPrice = this.allPriceNumber(index)
      } else {
        this.listData[index].tax = '0'
        this.listData[index].taxAllPrice = '0'
        this.listData[index].allPrice = '0'
      }

      this.$nextTick(() => {
        this.formData.tax = 0
        this.formData.allPrice = 0
        this.formData.taxAllPrice = 0
        this.listData.forEach(item => {
          this.formData.tax = new Big(this.formData.tax).plus(Number(item.tax ? item.tax : 0)).toString()
          this.formData.allPrice = new Big(this.formData.allPrice).plus(Number(item.allPrice ? item.allPrice : 0)).toString()
          this.formData.taxAllPrice = new Big(this.formData.taxAllPrice).plus(Number(item.taxAllPrice ? item.taxAllPrice : 0)).toString()
        })
      })
    },
    setFileName(...data) {
      this.formData.fileName = data[0]
      this.formData.fileRealName = data[1]
      this.formData.url = data[2]
    },
    headStyle() {
      return 'text-align:center'
    },
    importData() {

    },
    getList() {
      list(this.pageData).then(res => {
        this.peopleList = res.data
      })
    },
    cellClassName(data) {
      if (data.column.property == 'operate') {
        if (data.rowIndex % 2 == 0) {
          // 单数行
          return 'fixed one'
        } else {
          // 双数行
          return 'fixed two'
        }
      }
    },
    rowClassName({ row, rowIndex }) {
      if (rowIndex == this.tableData.length - 1) {
        return 'addRow'
      }
    },
    removeRow(row) {
      this.tableData.splice(this.tableData.indexOf(row), 1)
    },
    addRow() {
      this.saveData = this.$deepClone(this.listData)
      this.$layer.iframe({
        // 弹框
        content: {
          content: searchMaterial, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            // selectedRow: this.listData
            selectedRow: []
          } // props
        },
        area: ['1320px', '800px'],
        title: '选择销售订单明细', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    selectionChange1(rows) {
      this.selectionsAll1 = rows
    },
    deleteRow() {
      this.selectionsAll1.forEach(item => {
        this.listData.splice(this.listData.indexOf(item), 1)
      })
      this.$nextTick(() => {
        this.formData.tax = 0
        this.formData.allPrice = 0
        this.formData.taxAllPrice = 0
        this.listData.forEach(item => {
          this.formData.tax = new Big(this.formData.tax).plus(Number(item.tax ? item.tax : 0)).toString()
          this.formData.allPrice = new Big(this.formData.allPrice).plus(Number(item.allPrice ? item.allPrice : 0)).toString()
          this.formData.taxAllPrice = new Big(this.formData.taxAllPrice).plus(Number(item.taxAllPrice ? item.taxAllPrice : 0)).toString()
        })
      })
      // this.listData = this.listData.filter((ele) => this.selectionsAll.every((item) => ele.id !== item.id))
    },
    getInfo() {
      getInfo(this.id).then((res) => {
        Object.keys(this.formData).forEach((key) => {
          // 给右边数据赋值
          this.formData[key] = res.data[key]
        })
        this.listData = this.formData.data
        if (this.listData.length > 9) {
          this.tableHeight = '500'
        }
        this.saveData = this.$deepClone(this.listData)
        if (!this.formData.saleCustomerListVo) {
          this.formData.saleCustomerListVo = {
            taxTypeLabel: '',
            taxRateLabel: '',
            settlementTypeLabel: '',
            settlementCurrencyLabel: ''
          }
        }
        if (!this.formData.defaultSaleDeliverInformation) {
          this.formData.defaultSaleDeliverInformation = {
            deliveryTypeLabel: '',
            consignee: '',
            phone: '',
            deliveryAddress: '',
            attentionMatters: ''
          }
        }
        this.$nextTick(() => {
          this.fixAccuracyIssues()
        })
      })
    },
    chooseWays() {
      if (this.formData.saleCustomerId) {
        this.$layer.iframe({
          // 弹框
          content: {
            content: chooseWay, // 传递的组件对象
            parent: this, // 当前的vue对象
            data: {
              id: this.formData.saleCustomerId,
              selectionId: this.formData.saleCustomerSendInformationId ? this.formData.saleCustomerSendInformationId : ''
            } // props
          },
          area: ['880px', '800px'],
          title: '选择交货方式', // 标题
          shadeClose: false // 点击遮罩是否关闭
        })
      } else {
        this.$message.warning('请选择客户名称')
        return
      }
    },
    choosePeople() {
      this.$layer.iframe({
        // 弹框
        content: {
          content: seachUser, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            id: this.formData.saleCustomerId ? this.formData.saleCustomerId : ''
          } // props
        },
        area: ['880px', '800px'],
        title: '选择客户', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    dateDiff(d1, d2) {
      const start_at = new Date(d1.replace(/^(\d{4})(\d{2})(\d{2})$/, '$1/$2/$3'))
      const end_at = new Date(d2.replace(/^(\d{4})(\d{2})(\d{2})$/, '$1/$2/$3'))
      if (start_at > end_at) {
        return false
      }
      return true
    },
    // 提交
    onSubmit(num) {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.listData.length <= 0) { // 校验订单明细不能为空
            this.$message.warning('请添加销售订单明细')
            return
          }
          if (this.listData && this.listData.filter(item => !item.orderNumber).length > 0) {
            this.$message.warning('订单数量不能为空')
            return
          } else if (this.listData && this.listData.filter(item => item.orderNumber && !this.SETTINGS.reg_no_zero.test(item.orderNumber)).length > 0) {
            this.$message.warning('订单数量未正确填写')
            return
          } else if (this.listData && this.listData.filter(item => item.price && !this.SETTINGS.reg_zero.test(item.price)).length > 0) {
            this.$message.warning('未税单价未正确填写')
            return
          } else if (this.listData && this.listData.filter(item => item.taxPrice && !this.SETTINGS.reg_zero.test(item.taxPrice)).length > 0) {
            this.$message.warning('含税单价未正确填写')
            return
          } else if (this.listData && this.listData.filter(item => !item.saleCustomerDeliveryTime).length > 0) {
            this.$message.warning('客户交期不能为空')
            return
          }
          if (this.listData.filter(item => item.saleCustomerDeliveryTime >= this.formData.orderGoodsTime).length == 0) {
            this.$message.warning('客户交期不得小于订货日期')
            return
          }
          if (num == '1') {
            this.formData.orderTime = this.formData.orderTime ? moment(this.formData.orderTime).format('YYYY-MM-DD') : new Date()
          }
          this.formData.orderGoodsTime = this.formData.orderGoodsTime ? moment(this.formData.orderGoodsTime).format('YYYY-MM-DD') : ''
          this.listData.forEach(ele => {
            // ele['status'] = '0'
            if (!this.formData.id) {
              delete ele.id
            } else {
              this.listData.some(ele => {
                const data = this.saveData.find(item => item.materialId == ele.materialId)
                if (!data) {
                  delete ele.id
                }
              })
            }
            // ele.saleCustomerDeliveryTime = ele.saleCustomerDeliveryTime ? moment(ele.saleCustomerDeliveryTime).format('YYYY-MM-DD') : ''
          })

          // if (this.settingList.length > 0) {
          // orderapproval().then(res => {
          //   if (res.data || num == '0') {
          //     this.formData.data = this.$deepClone(this.listData)
          //     addOrUpdate({ ...this.formData, status: num }).then((res) => {
          //       this.$message({
          //         message: res.msg,
          //         type: 'success'
          //       })
          //       this.$layer.close(this.layerid) // 关闭弹框
          //       this.$parent.getList() // 调用父组件的刷新方法
          //     })
          //   } else {
          //     this.$message.warning('未设置审批人，无法提交')
          //     return
          //   }
          // })
          // }
          this.formData.data = this.$deepClone(this.listData)
          addOrUpdate({ ...this.formData, status: num }).then((res) => {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.$layer.close(this.layerid) // 关闭弹框
            this.$parent.getList() // 调用父组件的刷新方法
          })
        }
      })
    },
    cancel() {
      this.$layer.close(this.layerid) // 关闭弹框
    },
    chooseCustomer(data) {
      this.formData.saleCustomerId = data.id
      this.formData.customerName = data.name
      this.formData.saleCustomerListVo.taxTypeLabel = data.taxTypeLabel
      this.formData.saleCustomerListVo.taxRateLabel = data.taxRateLabel
      this.formData.saleCustomerListVo.settlementTypeLabel = data.settlementTypeLabel
      this.formData.saleCustomerListVo.settlementCurrencyLabel = data.settlementCurrencyLabel
      if (data.defaultSaleDeliverInformation) {
        this.formData.saleCustomerSendInformationId = data.defaultSaleDeliverInformation.id
        this.formData.defaultSaleDeliverInformation.deliveryTypeLabel = data.defaultSaleDeliverInformation.deliveryTypeLabel
        this.formData.defaultSaleDeliverInformation.consignee = data.defaultSaleDeliverInformation.consignee
        this.formData.defaultSaleDeliverInformation.phone = data.defaultSaleDeliverInformation.phone
        this.formData.defaultSaleDeliverInformation.deliveryAddress = data.defaultSaleDeliverInformation.deliveryAddress
        this.formData.defaultSaleDeliverInformation.attentionMatters = data.defaultSaleDeliverInformation.attentionMatters
      } else {
        this.formData.saleCustomerSendInformationId = ''
        this.formData.defaultSaleDeliverInformation.deliveryTypeLabel = ''
        this.formData.defaultSaleDeliverInformation.consignee = ''
        this.formData.defaultSaleDeliverInformation.phone = ''
        this.formData.defaultSaleDeliverInformation.deliveryAddress = ''
        this.formData.defaultSaleDeliverInformation.attentionMatters = ''
      }
      const arr2 = this.listData.map(item => item.materialId)
      listPriceByCustomer({
        customerId: this.formData.saleCustomerId,
        materialIds: _.uniq(arr2)
      }).then(res => {
        const arr = this.$deepClone(this.listData)
        arr.some(ele => {
          const data2 = res.data.find(item => item.materialInformationId == ele.materialId)
          if (data2) {
            ele.price = data2.price ? data2.price : '0'
            ele.taxPrice = data2.taxPrice ? data2.taxPrice : '0'
            ele.taxRateCode = data2.taxRateCode ? data2.taxRateCode : ''
            ele.taxRateLabel = data2.taxRateLabel ? data2.taxRateLabel : '0'
            ele.tax = ele.price && ele.taxRateLabel && ele.orderNumber ? new Big(ele.price).times(ele.taxRateLabel).div(100).times(ele.orderNumber).toString() : '0'
            ele.taxAllPrice = ele.taxPrice && ele.orderNumber ? new Big(ele.taxPrice).times(ele.orderNumber).toString() : '0'
            ele.allPrice = ele.price && ele.orderNumber ? new Big(ele.price).times(ele.orderNumber).toString() : '0'
            ele.saleCustomerMaterialCode = data2.saleCustomerMaterialCode ? data2.saleCustomerMaterialCode : ''
          } else {
            ele.price = '0'
            ele.taxPrice = '0'
            ele.taxRateCode = ''
            ele.taxRateLabel = '0'
            ele.tax = '0'
            ele.taxAllPrice = '0'
            ele.allPrice = '0'
            ele.saleCustomerMaterialCode = ''
          }
        })
        console.log(1111, arr)
        this.listData = arr
        this.tableKey = Math.random()
        this.$nextTick(() => {
          this.formData.tax = 0
          this.formData.allPrice = 0
          this.formData.taxAllPrice = 0
          this.listData.forEach(item => {
            this.formData.tax = new Big(this.formData.tax).plus(Number(item.tax ? item.tax : 0)).toString()
            this.formData.allPrice = new Big(this.formData.allPrice).plus(Number(item.allPrice ? item.allPrice : 0)).toString()
            this.formData.taxAllPrice = new Big(this.formData.taxAllPrice).plus(Number(item.taxAllPrice ? item.taxAllPrice : 0)).toString()
          })
        })
      })
    },
    showWayInfo(data) {
      this.formData.saleCustomerSendInformationId = data.id
      this.formData.defaultSaleDeliverInformation.deliveryTypeLabel = data.deliveryTypeLabel
      this.formData.defaultSaleDeliverInformation.consignee = data.consignee
      this.formData.defaultSaleDeliverInformation.phone = data.phone
      this.formData.defaultSaleDeliverInformation.deliveryAddress = data.deliveryAddress
      this.formData.defaultSaleDeliverInformation.attentionMatters = data.attentionMatters
    },
    showMaterial(data2, oldData) {
      console.log('data2', data2)
      console.log('oldData', oldData)
      // 不能直接替换，如果之前已经添加过，之前填的东西要保留
      // const cacheData = []
      // data2.forEach((item, index) => {
      //   if (this.listData.some(item2 => item2.materialId == item.materialId)) {
      //     cacheData.push(this.listData.filter(item2 => item2.materialId == item.materialId)[0])
      //   } else {
      //     // item.remark = ''
      //     item.status = 0
      //     cacheData.push(item)
      //   }
      //   if (index == data2.length - 1) {
      //     this.listData = this.$deepClone(cacheData)
      //   }
      // })
      // this.listData = cacheData
      // const differentObjects = data2.filter(obj1 => {
      //   return !oldData.some(obj2 => obj1.materialId === obj2.materialId)
      // })
      // const arr = differentObjects.map(item => item.materialId)
      // listPriceByCustomer({
      //   customerId: this.formData.saleCustomerId,
      //   materialIds: arr
      // }).then(res => {
      //   const arr = this.$deepClone(this.listData)
      //   arr.some(ele => {
      //     const data = res.data.find(item => item.materialInformationId == ele.materialId)
      //     console.log(data)
      //     if (data) {
      //       ele.price = data.price ? data.price : '0'
      //       ele.taxPrice = data.taxPrice ? data.taxPrice : '0'
      //       ele.taxRateCode = data.taxRateCode ? data.taxRateCode : ''
      //       ele.taxRateLabel = data.taxRateLabel ? data.taxRateLabel : '0'
      //       ele.saleCustomerMaterialCode = data.saleCustomerMaterialCode ? data.saleCustomerMaterialCode : ''
      //     }
      //   })
      //   this.listData = arr
      //   this.tableKey = Math.random()
      //   console.log(this.listData)
      // })

      // 物料可以重复选择，设置不同的客户交期   2024-4-22  需求变更
      // data2.map((item) => {
      //   item.status = 0
      //   this.listData.push(item)
      // })
      //
      const cacheData = this.$deepClone(data2)
      cacheData.map((item) => {
        item.status = 0
      })

      const arr2 = cacheData.map(item => item.materialId)
      if (this.formData.saleCustomerId) {
        listPriceByCustomer({
          customerId: this.formData.saleCustomerId,
          materialIds: _.uniq(arr2)
        }).then(res => {
          const arr = this.$deepClone(cacheData)
          arr.some(ele => {
            const data = res.data.find(item => item.materialInformationId == ele.materialId)
            if (data) {
              ele.price = data.price ? data.price : '0'
              ele.taxPrice = data.taxPrice ? data.taxPrice : '0'
              ele.taxRateCode = data.taxRateCode ? data.taxRateCode : ''
              ele.taxRateLabel = data.taxRateLabel ? data.taxRateLabel : '0'
              ele.saleCustomerMaterialCode = data.saleCustomerMaterialCode ? data.saleCustomerMaterialCode : ''
            }
          })
          this.listData.push(...arr)
          this.tableKey = Math.random()
        })
      } else {
        this.listData.push(...cacheData)
        this.tableKey = Math.random()
      }
    },
    summaryMethod({ columns, data }) {
      const means = [] // 合计
      columns.forEach((column, columnIndex) => {
        if (columnIndex === 0) {
          means.push('合计')
        } else {
          if (column.property == 'tax' || column.property == 'allPrice' || column.property == 'taxAllPrice' || column.property == 'orderNumber') {
            const values = data.map(item => Number(item[column.property]))
            // 合计
            if (!values.every(value => isNaN(value))) {
              means[columnIndex] = values.reduce((prev, curr) => {
                const value = Number(curr)
                if (!isNaN(value)) {
                  // return prev + curr
                  return Number((new Big(prev).plus(curr)).toString())
                } else {
                  return prev
                }
              }, 0)
            } else {
              means[columnIndex] = ''
            }
            switch (column.property) {
              case 'tax':
                this.formData.tax = means[columnIndex]
                break
              case 'allPrice':
                this.formData.allPrice = means[columnIndex]
                break
              case 'taxAllPrice':
                this.formData.taxAllPrice = means[columnIndex]
                break
            }
          }
        }
      })
      return [means]
    },
    // 修复精度问题
    fixAccuracyIssues() {
      const cells = document.querySelectorAll('.el-table__footer-wrapper .el-table__footer .cell')
      cells.forEach(item => {
        if (item.offsetHeight > 0 && item.textContent != '合计') {
          const thisClass = '.' + Array.from(item.offsetParent.classList).join('.')
          // 选择多级 class 选择器的元素
          const grandchildElement = document.querySelector('.el-table__footer-wrapper .el-table__footer ' + thisClass + ' .cell')
          const thisNumber = checkAndFixPrecision(Number(item.textContent))
          console.log('item', item)
          console.log('thisNumber', thisNumber)
          // 设置内容
          grandchildElement.textContent = thisNumber
        }
      })
    },
    tableBodyScroll({ scrollTop, scrollLeft }) {
      this.table_scrollTop = scrollTop
      this.table_scrollLeft = scrollLeft
    }
  }
}
function checkAndFixPrecision(value, precision = 5) {
  // 将数字转换为字符串
  const valueStr = value.toString()
  if (!valueStr.includes('.')) {
    return value
  }
  const valueStrRight = valueStr.split('.')[1]

  // 检查是否存在精度丢失
  if (valueStrRight.length > precision) {
    // 如果存在精度丢失，则进行修复
    const fixedValue = parseFloat(value.toFixed(precision - 1))
    return fixedValue
  }

  // 如果没有精度丢失，返回原值
  return value
}
</script>

<style lang="less" scoped>
///deep/.is-leaf {
//  text-align: left !important;
//}
.main_bottom{
  justify-content: space-between;
}
/deep/ .u-table__fixed-footer-wrapper {
  .u-table__cell:last-of-type {
    height: 39px !important;
  }
}
.customer_info{
  margin-top: 15px;
}
/deep/ .el-tabs__header{
  margin: 0 !important;
}
/deep/ .el-tabs__content{
  padding: 0 16px !important;
}
.form_item{
  border-bottom: 1px solid #D6D6D6;
  // width: 100%;
  border-bottom: 1px solid #D6D6D6;
  margin-left: 0;
  margin-right: 0;
  margin-bottom: 0;
  /deep/ .el-form-item__label:before{
    content: none;
  }
  /deep/ .el-form-item__label{
    color: #1F51B3;
    font-size: 15px;
  }
  /deep/ .el-form-item__label{
    width: 140px !important;
    margin-top: 10px;
  }
  /deep/ .el-form-item__content{
    color: #333333;
    font-size: 15px;
    flex: 1;
    width: unset;
    margin-top: 10px;
    margin-right: 0px;
  }
}
.title {
  padding-left: 20px;
  padding-bottom: 20px;
  font-size: 24px;
  width: 100%;
}
.numberComponents {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
}
/deep/ .el-input-number.is-controls-right .el-input-number__increase {
  height: 15px;
}
.el-icon-remove {
  font-size: 25px;
  color: red;
  height: 100%;
  width: 100%;
  border: 0px;
  background-color: transparent;
}
/deep/ .el-form-item__content {
  margin-left: 0 !important;
}
/deep/ .el-form-item__label {
  text-align: right;
}
.expand_radio {
  /deep/ .el-form-item__content {
    text-align: left;
  }
}
.expand_container {
  .el-form-item {
    margin-bottom: 10px;
  }
  .expand_file {
    margin-bottom: 0px;
  }

  /deep/ .el-form-item__label {
    width: 130px !important;
  }
  /deep/ .el-form-item__content {
    width: 710px !important;
  }
}
.main_main {
  padding-top:0 !important ;
  height: 100%;
  .form_padding {
    padding: 0 !important;
    /deep/ .el-form-item {
      margin-right: 0px;
    }
    /deep/ .el-form-item__label {
      width: 120px !important;
    }
    /deep/ .el-form-item__content {
      width: 270px;
    }
    .remark {
      /deep/ .el-form-item__content {
        width: 690px !important;
        height: 60px;
        overflow-y: auto;
      }
    }
  }
}
/deep/ .u-table th.u-table__cell > .cell {
  position: unset;
}
.order_header{
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  .info_button{
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-end;
  }
}
///deep/ .u-table__footer-wrapper{
//  width: calc(100% - 8px);
//}

//// 滚动条的宽度
///deep/ .u-table__body-wrapper::-webkit-scrollbar {
//  width: 0px; // 横向滚动条
//}
///deep/ .u-table__body-wrapper {
//
//  width: calc(100% - 8px);
//}
//
////注意:hover
///deep/ .u-table__body-wrapper:hover::-webkit-scrollbar {
//  width: 8px; // 横向滚动条
//}
///deep/ .u-table__body-wrapper:hover{
//  width: 100%;
//}

</style>
